<?php

namespace app\qsapi\service;

use app\qsapi\model\BoxGame;
use app\qsapi\model\BoxMemberInfo;
use app\qsapi\model\BoxYunGoods;
use app\qsapi\model\BoxYunOrder;
use app\qsapi\model\BoxYunOrderMachine;
use app\qsapi\model\BoxYunUserMachine;
use app\qsapi\model\Member;
use app\util\Common;
use think\cache\driver\Redis;
use think\Db;
use think\Exception;
use think\exception\DbException;

class BoxYunOrderService extends BaseService
{

    /**
     * Notes: 下单
     * User: liubaoqiang
     * DateTime: 2024/12/11 10:11
     * @param $member_id
     * @param $param
     * @return array
     */
    public function yunMakeOrder($member_id, $param): array
    {
        //=======用户防刷操作redis=======
        $redis = new Redis(getRedisConfig());
        if ($redis->get('user_yun_make_order:' . $member_id)) {
            return api_message([], '操作过于频繁', 0);
        }
        $redis->set('user_yun_make_order:' . $member_id, $member_id, 5);
        //=======用户防刷操作redis==========

        $required_fields = ['goods_id', 'num', 'yun_type', 'os'];
        foreach ($required_fields as $field) {
            if (!isset($param[$field])) {
                return api_message([], "缺少 '$field' 参数！", 0);
            }
        }

        if ($param['yun_type'] == '2' && empty($param['facilities_id'])) {
            return api_message([], "请选择设备", 0);
        }

        if ($param['yun_type'] == '2') {  //yun_type == 2  续费操作

            //查询此设备
            $yunDevice['facilitiesId'] = (string)$param['facilities_id'];
            $yunDevice['os']           = (string)$param['os'];

            $yunData = YunService::getUserFacilitiesList($member_id, $yunDevice);
            if ($yunData['code'] != '1') {
                return api_message([], $yunData['message'], 0);
            }
            if (empty($yunData['data'])) {
                return api_message([], '无此设备', 0);
            }
            if ($yunData['data'][0]['status'] == '-50') {
                return api_message([], '设备已过期/注销', 0);
            }

        }
        $goodsInfo = BoxYunGoods::where('id', $param['goods_id'])->find();
        if (empty($goodsInfo)) {
            return api_message([], "无此商品", 0);
        }
        if (empty($goodsInfo['remaining_stock'])) {
            return api_message([], "此商品无库存", 0);
        }
        $ip = get_client_ip();
        if (!empty($goodsInfo['ip_whitelist']) && $goodsInfo['ip_whitelist'] != $ip) {
            return api_message([], "非法操作", 0);
        }
        $vip_growth = BoxMemberInfo::where('member_id',$member_id)->value('vip_growth') ?? 0;
        Db::startTrans();
        try {

            $orderModel              = new BoxYunOrder();
            $orderModel->order_num   = self::generateOrderNum($member_id);
            $orderModel->member_id   = $member_id;
            $orderModel->goods_id    = $param['goods_id'];
            $orderModel->num         = $param['num'];
            $orderModel->yun_type    = $param['yun_type'];
            $orderModel->price       = $goodsInfo['price'] * $param['num'];
            $orderModel->status      = 1;
            $orderModel->create_time = date("Y-m-d H:i:s");
            $orderModel->os          = $param['os'];
            $orderModel->client_ip   = get_client_ip();
            $orderModel->vip_growth   = $vip_growth;
            if (!$orderModel->save()) {
                write_log('INFO', 'BoxYunOrderService.php', 'yunMakeOrder::创建订单报错' . $orderModel->getError(), 'BoxYunOrderMachine', true);
                throw new Exception("获取奖励失败", 0);
            }

            $machine['yun_order_id'] = $orderModel->id;
            $machine['member_id']    = $member_id;
            $machine['os']           = $param['os'];
            $machine['client_ip']    = get_client_ip();

            if ($param['yun_type'] == '2') {
                $machineModel             = new BoxYunOrderMachine();
                $machine['type']          = 2;
                $machine['duration']      = $goodsInfo['duration'] * $param['num'];
                $machine['facilities_id'] = $yunData['data'][0]['facilitiesId'];
                $machine['user_phone_id'] = $yunData['data'][0]['userPhoneId'];
                $machine['create_time']   = date('Y-m-d H:i:s');
                if (!$machineModel->save($machine)) {
                    write_log('INFO', 'BoxYunOrderService.php', 'yunMakeOrder::续费云挂机报错' . $machineModel->getError(), 'BoxYunOrderMachine', true);
                    throw new Exception("下单失败！" . $machineModel->getError(), 0);
                }
            }
            //扣除库存
            $kuCun = BoxYunGoods::where('id', $param['goods_id'])->value('remaining_stock');
            if ($kuCun < $param['num'] || $kuCun == 0) {
                throw new Exception("库存不足,请减少你的购买数量", 0);
            }
            $stockDeduct = BoxYunGoods::where('id', $param['goods_id'])->where('remaining_stock', '>', 0)->setDec('remaining_stock', $param['num']);
            if (!$stockDeduct) {
                throw new Exception("下单失败,暂无库存！", 0);
            }
            $data = [
                'order_num' => $orderModel->order_num
            ];
            Db::commit();
            return api_message($data, '下单成功！');
        } catch (Exception $e) {
            Db::rollback();
            return api_message([], $e->getMessage(), 0);
        }
    }


    //生成订单号
    private static function generateOrderNum($userId)
    {
        $orderNum = "QNYGJ_" . date("Ymd") . $userId . str_pad(rand(1, 9999), 4, 0, STR_PAD_LEFT);
        //查询订单号是否存在
        $exit = BoxYunOrder::where(['order_num' => $orderNum])->find();
        if (!empty($exit)) {
            self::generateOrderNum($userId);
        } else {
            return $orderNum;
        }
    }


    /**
     * @Notes:订单列表
     * @Interface getYunOrderList
     * @param $member_id
     * @param $param
     * @return array
     * @throws DbException
     */
    public function getYunOrderList($member_id, $param): array
    {
        $limit = $param['limit'] ?? 10;
        $list  = Db::name('box_yun_order')->alias('o')
            ->field(['o.id,o.order_num,o.member_id,o.goods_id,g.name,o.price,o.status,o.create_time,o.pay_time'])
            ->leftJoin('box_yun_goods g', 'g.id = o.goods_id')
            ->where(['o.member_id' => $member_id])
            ->whereIn('o.status', ['2', '3'])
            ->whereIn('o.yun_type',[1 , 2])
            ->order('o.create_time', 'desc')
            ->paginate($limit);
        if (empty($list)) {
            return api_message([], '暂无数据', 0);
        }
        $list = $list->toArray();

        foreach ($list['data'] as &$value) {
            $info                = BoxYunOrderMachine::where(['yun_order_id' => $value['id']])->find();
            $value['start_time'] = $info['start_time'] == "0000-00-00 00:00:00" ? '' : $info['start_time'];
            $value['end_time']   = $info['end_time'] == "0000-00-00 00:00:00" ? '' : $info['end_time'];
        }
        return api_message($list, '操作成功');
    }

    /**
     * @Notes:订单详情
     * @Interface getYunOrderDetail
     */
    public function getYunOrderDetail($member_id, $param)
    {
        $order_num = $param['order_num'] ?? '';
        if (empty($order_num)) {
            return api_message([], '请选择订单', 0);
        }
        $info = Db::name('box_yun_order')->alias('o')
            ->field(['o.id,o.order_num,o.member_id,o.num,o.goods_id,g.name,o.price,o.status,o.create_time,o.pay_time,o.pay_type,o.yun_type,UNIX_TIMESTAMP(o.create_time)*1000 created_at'])
            ->leftJoin('box_yun_goods g', 'g.id = o.goods_id')
            ->where(['o.member_id' => $member_id, 'o.order_num' => $order_num])
            ->find();
        if (empty($info)) {
            return api_message([], '暂无数据', 0);
        }

        $machine            = BoxYunOrderMachine::where(['yun_order_id' => $info['id']])->find();
        $info['start_time'] = $machine['start_time'] == "0000-00-00 00:00:00" ? '' : $machine['start_time'];
        $info['end_time']   = $machine['end_time'] == "0000-00-00 00:00:00" ? '' : $machine['end_time'];
//        $info['status']   = BoxYunOrder::$order_status[$info['status']];
        $info['pay_type'] = BoxYunOrder::$pay_type[$info['pay_type']];
        $info['yun_type'] = BoxYunOrder::$yun_type[$info['yun_type']];
        return api_message($info, '操作成功');
    }


    /**
     * Desc : 获取商品购买上限
     * User : you name
     * Date : 2024-04-11 11:14
     * @param $member_id
     * @param $param
     * @return array
     */
    public function purchaseUpperLimit($member_id, $param): array
    {
        $goods_id = $param['goods_id'] ?? 0;
        if (empty($member_id) || empty($goods_id)) {
            return api_message([], '参数错误', 0);
        }
        try {
            $goodsInfo = BoxYunGoods::where(['id' => $goods_id])->find();
            if (empty($goodsInfo)) {
                return api_message([], '商品不存在', 0);
            }
            $goodsInfo                    = $goodsInfo->toArray();
            $goodsInfo['remaining_stock'] = $goodsInfo['remaining_stock'] ?? 0;
            $cycle                        = $goodsInfo['cycle'] ?? 0;
            $limit                        = $goodsInfo['limit'] ?? 0;
            if ($goodsInfo['remaining_stock'] < $limit) {
                return api_message([], '库存不足', 0);
            }

            //查找当前用户当前商品购买的数量
            $map = [
                ['member_id', '=', $member_id],
                ['goods_id', '=', $goods_id],
                ['status', '=', 3],
                ['pay_status', '=', 1],
                ['yun_type', '=', 1]
            ];
            //限购周期，0、不限购，1、永久, 2、天，3、周，4、月'
            switch ($cycle) {
                case 1: //永久
                    break;
                case 2: //天
                    $map[] = ['pay_time', '>=', date('Y-m-d') . ' 00:00:00'];
                    $map[] = ['pay_time', '<=', date('Y-m-d') . ' 23:59:59'];
                    break;
                case 3: //周
                    $start_time = date('Y-m-d H:i:s', strtotime('this week monday'));
                    $end_time   = date('Y-m-d H:i:s', strtotime('this week sunday 23:59:59'));
                    $map[]      = ['pay_time', '>=', $start_time];
                    $map[]      = ['pay_time', '<=', $end_time];
                    break;
                case 4: //月
                    $start_time = strtotime(date('Y-m-01')); // 获取本月第一天的0点时间戳
                    $end_time   = strtotime('+1 month', $start_time) - 1; // 获取下月的第一天减一，即本月最后一天的最后一秒
                    $map[]      = ['pay_time', '>=', date('Y-m-01') . ' 00:00:00'];
                    $map[]      = ['pay_time', '<=', date('Y-m-d' . ' 23:59:59', $end_time)];
                    break;
            }

            $orderModel = new BoxYunOrder();
            $count      = $orderModel->where($map)->count();
            if ($count < $limit) {
                $item['can_purchase_num'] = intval($limit - $count);  //还能购买的数量
                $item['purchase_status']  = 1;      //是否可购买; 0:不可购买; 1:可购买
            } else {
                $item['can_purchase_num'] = 0;
                $item['purchase_status']  = 0;
            }
            return api_message($item, '操作成功');

        } catch (Exception $e) {
            return api_message([], $e->getMessage(), 0);
        }
    }


}
